package com.hxd.qzg.module;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.hxd.qzg.common.Operation;
import com.hxd.qzg.common.ServiceException;
import com.hxd.qzg.common.UseBox;
import com.hxd.qzg.common.enums.BoxStatusEnum;
import com.hxd.qzg.common.model.Box;
import com.hxd.qzg.common.model.BoxGroup;
import com.hxd.qzg.common.model.Certificate;
import com.hxd.qzg.common.model.PayInfo;
import com.hxd.qzg.common.vo.BoxGroupVO;
import com.hxd.qzg.common.vo.BoxListVO;
import com.hxd.qzg.common.vo.BoxStatusVO;
import com.hxd.qzg.common.vo.BoxVO;
import com.hxd.qzg.common.vo.CertificateVO;
import com.hxd.qzg.common.vo.PayInfoVO;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hutool.core.util.IdUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class BoxGroupService {

	private static final Log logger = LogFactory.get();

	// 获取分组信息并且显示 各个状态下的柜子数量
	public List<BoxGroupVO> listBoxGroup() {
		// 查询所有分组
		List<BoxGroup>  boxGroups=BoxGroup.dao.findAll();

		// 转化类型
		List<BoxGroupVO> boxGroupVOs = new ArrayList<BoxGroupVO>();
		for (BoxGroup boxGroup : boxGroups) {
			BoxGroupVO boxGroupVO=new BoxGroupVO();
			boxGroupVO.setId(boxGroup.getId());
			boxGroupVO.setName(boxGroup.getName());
			List<Record> records = Db.find(
					"SELECT COUNT(*) count ,status  FROM  api_box  WHERE box_group_id=? GROUP BY STATUS ",
					boxGroupVO.getId());
			List<BoxStatusVO> boxStatusVOs = new ArrayList<BoxStatusVO>();

			for (BoxStatusEnum boxStatusEnum : BoxStatusEnum.values()) {
				BoxStatusVO boxStatusVO = new BoxStatusVO();
				boxStatusVO.setStatus(boxStatusEnum.getCode());
				boxStatusVO.setStatusName(boxStatusEnum.getDescription());
				for (Record record : records) {
					if (record.getInt("status") == boxStatusVO.getStatus()) {
						boxStatusVO.setCount(record.getInt("count"));
					}
				}
				boxStatusVOs.add(boxStatusVO);
			}

			boxGroupVO.setBoxStatusVOs(boxStatusVOs);
			boxGroupVOs.add(boxGroupVO);
		}
		return boxGroupVOs;
	}

	// 首页显示 盒子情况
	public BoxListVO list(Integer boxGroupId) {
		BoxListVO boxListVO = new BoxListVO();
		boxListVO.setBoxs(this.listBox(boxGroupId));
		boxListVO.setBoxStatusVOs(this.listBoxStatus(boxGroupId));
		return boxListVO;
	}
	
	
	
	// 显示分组内柜子情况
	public List<Box> listBox(Integer boxGroupId) {
		List<Record> records = Db.find("SELECT id ,status, name,ban,box_no   FROM  api_box  WHERE box_group_id=? ",
				boxGroupId);
		List<Box> list = new ArrayList<Box>();
		for (Record record : records) {
			Box box = new Box();
			box.setId(record.getLong("id"));
			box.setStatus(record.getInt("status"));
			box.setName(record.getStr("name"));
			box.setBan(record.getStr("ban"));
			box.setBoxNo(record.getStr("box_no"));

			list.add(box);
		}

		return list;
	}

	// 显示分组内柜子情况
	public List<BoxStatusVO> listBoxStatus(Integer boxGroupId) {
		List<BoxStatusVO> list = new ArrayList<BoxStatusVO>();
		List<Record> records = Db.find(
				"SELECT COUNT(*) count ,status  FROM  api_box  WHERE box_group_id=? GROUP BY STATUS ", boxGroupId);

		BoxStatusEnum[] boxStatusEnums = BoxStatusEnum.values();
		for (BoxStatusEnum boxStatusEnum : boxStatusEnums) {
			BoxStatusVO boxStatusVO = new BoxStatusVO();
			boxStatusVO.setStatus(boxStatusEnum.getCode());
			boxStatusVO.setStatusName(boxStatusEnum.getDescription());
			for (Record record : records) {
				if (record.getInt("status") == boxStatusVO.getStatus()) {
					boxStatusVO.setCount(record.getInt("count"));
				}
			}
			list.add(boxStatusVO);
		}

		return list;
	}


	// 根据 柜子 id 显示当前柜子内的数据
	public BoxVO getBoxInfo(Integer boxId) {
		Box box = Box.dao.findById(boxId);
		if (box == null) {
			throw new ServiceException("找不到柜子数据");
		}

		BoxVO boxVO = new BoxVO();
		boxVO.setBoxId(boxId);
		boxVO.setName(box.getName());
		List<CertificateVO> certificateVOs = new ArrayList<CertificateVO>();

		// 盒子内信息假数据
		List<Record> records = Db.find(
				"SELECT id ,no,qlr,zl   FROM  api_certificate  WHERE box_id=? ", boxId);
		for (Record record : records) {
			CertificateVO certificateVO = new CertificateVO();
			certificateVO.setId(record.getInt("id"));
			certificateVO.setNo(record.getStr("no"));
			certificateVO.setQlr(record.getStr("qlr"));
			certificateVO.setZl(record.getStr("zl"));
			certificateVOs.add(certificateVO);
		}
		boxVO.setCertificateVOs(certificateVOs);
		return boxVO;
	}

	// 根据 柜子 id 开柜
	public boolean openbox(Integer boxId) {
		Box box = Box.dao.findById(boxId);
		if (box == null) {
			throw new ServiceException("找不到柜子数据");
		}
		box.setUpdateTime(new Date());
		box.setLastDate(new Date());
		boolean bool = box.update();
		return bool;
	}

	// 取box内的证书
	public boolean takeOutCertificate(Integer boxId) {

		Box box = Box.dao.findById(boxId);
		if (box == null) {
			throw new ServiceException("找不到柜子数据");
		}

		box.setStatus(BoxStatusEnum.NULL.getCode());
		box.setUpdateTime(new Date());
		box.setLastDate(new Date());
		boolean bool = box.update();
		if (!bool) {
			throw new ServiceException("当前盒子更改信息失败,");
		}
		logger.info("takeOutCertificate boxId {}", boxId);
		List<Record> records = Db.find("SELECT id ,no,qlr,zl   FROM  api_certificate  WHERE box_id=?", boxId);
		for (Record record : records) {
			Certificate certificate = new Certificate();
			certificate.setId(record.getInt("id"));
			certificate.setLastBoxId(boxId);
			certificate.setBoxId(0);
			certificate.update();
		}
		return bool;
	}

	// 扫码信息
	public List<CertificateVO> scan(Integer boxId, String scanInfo) {
		Box box = Box.dao.findById(boxId);
		if (box == null) {
			throw new ServiceException("找不到柜子数据");
		}
		if (StringUtils.isEmpty(scanInfo)) {
			throw new ServiceException("扫码信息错误");
		}

		// 假数据
		List<CertificateVO> certificateVOs = new ArrayList<CertificateVO>();

		List<Record> records = Db.find("SELECT id ,no,qlr,zl   FROM  api_certificate  limit 2");
		for (Record record : records) {
			CertificateVO certificateVO = new CertificateVO();
			certificateVO.setNo(record.getStr("no"));
			certificateVO.setQlr(record.getStr("qlr"));
			certificateVO.setZl(record.getStr("zl"));
			certificateVOs.add(certificateVO);
		}

		return certificateVOs;
	}

	// 确定扫码
	public boolean scanSave(Integer boxId, String scanInfo) {
		// 根据扫码信息 形成一笔订单
		String orderNo = scanInfo;

		Box box = Box.dao.findById(boxId);
		if (box == null) {
			throw new ServiceException("找不到柜子数据");
		}
		
		// 假数据
		List<Record> records = Db.find("SELECT id ,no,qlr,zl   FROM  api_certificate  limit 2");
		//确定入库
		Db.tx(() -> {
			for (Record record : records) {
				Certificate certificate = new Certificate();
				certificate.setNo(record.getStr("no"));
				certificate.setQlr(record.getStr("qlr"));
				certificate.setZl(record.getStr("zl"));
				certificate.setBoxId(boxId);
				boolean bl = certificate.save();
				if (!bl) {
					throw new ServiceException("certificate 保存错误,");
				}
			}
			Box bxBox = new Box();
			bxBox.setId(box.getId());
			bxBox.setUpdateTime(new Date());
			bxBox.setLastDate(new Date());
			bxBox.setStatus(BoxStatusEnum.TO_BE_COLLECTEDL.getCode());
			boolean bl = bxBox.update();
			if (!bl) {
				throw new ServiceException("box 保存错误,");
			}
			return true;
		});

		return false;
	}

	// 验证是否支付
	public boolean isPay(String scanInfo ) {
		// 扫码信息转化成订单编号
		String orderNo = scanInfo;
		Record record = Db.findFirst("SELECT id ,order_no,status,pay_type   FROM  api_order where order_no=?",
				orderNo);
		if (null == record) {
			throw new ServiceException("api_order 查询不到记录");
		}

		Integer status = record.getInt("status");
		// 创建状态 未支付
		if (status == 1) {
			return true;
		}
		throw new ServiceException("暂时未查到缴费信息,");

	}

	// 确定支付信息
	public PayInfoVO qRCode(String scanInfo, Integer type) {
		String orderNo = scanInfo;
		Record record = Db.findFirst("SELECT id ,order_no,status,pay_type ,trxamt  FROM  api_order where order_no=?",
				orderNo);
		if (null == record) {
			throw new ServiceException("order查询不到记录");
		}

		Integer status = record.getInt("status");
		// 创建状态 未支付
		if (status == 1) {
			throw new ServiceException("当前业务已结支付");
		}

		String trxamt = record.getStr("trxamt");

		// 创建支付信息
		PayInfoVO payInfoVO = new PayInfoVO();
		// 查询不到 就插入当前支付信息
		Record payInfo = Db.findFirst(
				"SELECT id ,order_no,status,pay_type,trxamt   FROM  api_pay_info where order_no=? AND pay_type=?",
				orderNo, type);
		if (null == payInfo) {
			PayInfo info = new PayInfo();
			info.setOrderNo(orderNo);
			info.setPayType(type);
			info.setBuyer("");
			info.setStatus(0);
			info.setTransactionNo(IdUtil.randomUUID());
			info.setTrxamt(Integer.valueOf(trxamt));
			info.save();
			payInfoVO.setId(String.valueOf(info.getId()));
			payInfoVO.setTrxamt(String.valueOf(trxamt));
			payInfoVO.setType(type);
			return payInfoVO;
		}
		payInfoVO.setId(payInfo.getStr("id"));
		payInfoVO.setTrxamt(payInfo.getStr("trxamt"));
		payInfoVO.setType(payInfo.getInt("pay_type"));
		return payInfoVO;

	}

	// 客户端开启柜子
	public boolean customerOpenBox(String scanInfo) {
		String orderNo = scanInfo;
		Record record = Db.findFirst(
				"SELECT id ,order_no,status,pay_type ,trxamt,box_id  FROM  api_order where order_no=?", orderNo);
		if (null == record) {
			throw new ServiceException("api_order 查询不到记录");
		}

		Integer status = record.getInt("status");

		// 创建状态 未支付
		if (status != 1) {
			throw new ServiceException("当前业务未支付");
		}
		Integer boxId = record.getInt("box_id");
		return true;
	}

	public void handle(Operation operation, int code) {
		boolean b1 = new UseBox().clickOperation(operation, code);
		if (!b1) {
			throw new ServiceException("当前业务出现错误");
		}
	}


}
